<?php
	
	class StudentTable extends ORM {
		
		const NAME = 'Student';
				
		static private $instance = NULL; 

		static public function getInstance() { 
			if (self::$instance == NULL) { 
				self::$instance = new StudentTable(); 
			} 
			return self::$instance; 
		} 
		
		public function getAllStudents(){
		
			$query = 'SELECT * from '.self::NAME;
			
			$res = $this->executeQuery($query);
			
			$aStudents = array();
			
			while ($row = mysql_fetch_assoc($res)){
				
				$aStudents[] = new Student($row['name'], $row['age'], $row['login'], $row['password'], $row['id']);	
			}
			
			return $aStudents;
		}
		
		public function addStudent(Student $student){
			$query = "INSERT INTO ".self::NAME."(name, age, login, password) VALUES ('".
				$student->name ."', '". 
				$student->age ."', '".
				$student->login ."', '".
				md5($student->password) ."')";
			
			$this->executeQuery($query);	
		}
		
		public function deleteStudent($studentId){
			$query = "DELETE FROM ".self::NAME." WHERE id=".$studentId;
			
			$this->executeQuery($query);	
		}
		
		public function editStudent(Student $student){
			$query = "UPDATE ".self::NAME." SET 
				name = '{$student->name}',  
				age='{$student->age}', 
				login='{$student->login}', 
				password='{$student->password}' 				
				WHERE id={$student->id}";
			
			$this->executeQuery($query);	
		}
		
		public function findStudentId($login, $password){
			
			$query = "SELECT id FROM ".self::NAME.
					" WHERE login='".$login."' AND ".
					"password = '".md5($password)."'";

			$result = $this->executeQuery($query);	
			
			if ($row = mysql_fetch_assoc($result)){
				
				return $row['id'];
			}
			
			return false;
		}
		
		public function findStudentById($id){
			
			$query = "SELECT * FROM ".self::NAME.
					" WHERE id='".$id."'";

			$result = $this->executeQuery($query);	
			
			if ($row = mysql_fetch_assoc($result)){
				
				return new Student($row['name'], $row['age'], $row['login'], $row['password'], $row['id']);			
			}
			
			return false;
		}
		
	}
	
?>